//
//  M_PayVC.swift
//  letuofu
//
//  Created by WH-JS on 2020/1/2.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_PayVC: BaseViewControllerWithHeader {
    var payData : [String:Any?]
    var timeCount = 60
    let timerBtn = Button()
    var timer : Timer?
    
    var vcodeField = TextField()
    
    func timerinvalidate() {
        timer?.invalidate()
        timer = nil
        print("\(self)已销毁")
    }
    
    override func _onBackButtonClick() {
        timerinvalidate()
        self.popViewController(vCount: 3)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    
    init(_ data : [String: Any?], price: String? = "") {
        self.payData = data
        self.payData.updateValue(price, forKey: "price")
        super.init()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func payAction(orderdata: [String:Any], callback: @escaping () -> Void) {
        MBProgressHUD.showOrIncrease()
        var params :[String:Any] = orderdata
        params.updateValue(LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "", forKey: "identityToken")
        API.request(url: .M_PayOrder, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                callback()
            }
            else {
                let popup = PopupSureBox(title: "支付失败，兑换码错误！", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
}

// MARK: setupUI
extension M_PayVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        headTitle.text = "手机验证兑换"
        
        let img = safeView.drawImage(named: "sjizhiyanzheng_95") { (make) in
            make.top.equalTo(headView.snp.bottom).offset(30)
            make.left.equalToSuperview().offset(120)
        }
        
        safeView.drawLabel(text: "通过手机验证", fontSize: 14, textColor: .x333333) { (make) in
            make.top.equalTo(img)
            make.left.equalTo(img.snp.right).offset(8.5)
        }
        
        var lab = safeView.drawLabel(text: "你需支付", fontSize: 14, textColor: .x333333) { (make) in
            make.bottom.equalTo(img)
            make.left.equalTo(img.snp.right).offset(8.5)
        }
        
        lab = safeView.drawLabel(text: payData.getString("price"), fontSize: 16, textColor: .xFC4C02) { (make) in
            make.bottom.equalTo(img)
            make.left.equalTo(lab.snp.right).offset(5)
        }
        
        let dl = LocalStorage.getDic(forKey: DEFULT_MALL)
        let centUnitName = dl?.getString("centName")
        safeView.drawLabel(text: centUnitName, fontSize: 14, textColor: .x333333) { (make) in
            make.bottom.equalTo(img)
            make.left.equalTo(lab.snp.right).offset(5)
        }
        
        let bgview = safeView.drawView { (make) in
            make.top.equalTo(img.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.height.equalTo(101)
        }
        bgview.backgroundColor = .white
        
        bgview.drawLabel(text: LocalStorage.getString(forKey: LOGIN_ID), fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        
        //画横线
        var line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(40)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview.drawTextField(textField: vcodeField, placeholder: "请输入验证码", fontSize: 12, fontWeight: .regular, keyboardType: .numberPad, returnKeyType: .done) { (make) in
            make.top.equalTo(line.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(10)
        }
        vcodeField.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        
        var btn = bgview.drawButton(button: timerBtn, title: "获取验证码", titleColor: .x333333, fontSize: 12) { (make) in
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(line.snp.bottom).offset(20)
        }
        btn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
        btn.addTarget(self, action: #selector(_vcodeButtonClick(button:)), for: .touchUpInside)
        
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalTo(vcodeField.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2

        btn = safeView.drawButton(title: "确认验证", titleColor: .white, fontSize: 15) { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(bgview.snp.bottom).offset(43)
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(35)
        }
        btn.backgroundColor = .xFC4C02
        btn.layer.cornerRadius = 7
        btn.addTarget(self, action: #selector(_submitButtonClick(button:)), for: .touchUpInside)
        
//        _vcodeButtonClick(button: Button())
    }
}

// MARK: event & action
extension M_PayVC {
    
    func sendNot() {
        let noT = NSNotification.Name(rawValue: PAY_SUCCEED)
        let dic = ["key":"value"]
        NotificationCenter.default.post(name: noT, object: nil, userInfo:dic)
    }
    
    func codeTimer() {
        timer=Timer.scheduledTimer(timeInterval:1, target:self, selector:#selector(functickDown), userInfo:nil, repeats:true)
        //开始计时器
        timeCount = 60
        timer?.fire()
    }
    
    @objc func _vcodeButtonClick(button: Button) {
        API.sendVerifyCode(pCode: "110001", callback: { (dic) in
            self.payData = self.payData.merging(dic ?? [:], uniquingKeysWith: {(_, key2) in
                return key2
            })
            self.codeTimer()
        })
    }
    
    @objc func _submitButtonClick(button: Button) {
        if vcodeField.text?.count ?? 0 == 0 {
            let popup = PopupBox(infoText: "请输入验证码")
            popup.show(vc: UIViewController.topMostController() ?? self)
            return
        }
        UIApplication.shared.keyWindow?.endEditing(true)
        self.payData.updateValue(vcodeField.text, forKey: "vaildeCode")
        payAction(orderdata: payData as [String : Any], callback: {
            self.sendNot()
            self.timerinvalidate()
            let vc = M_PaySucceedVC()
            vc.orderData = self.payData
            self.pushViewController(vc)
        })
    }
    
    @objc func functickDown(){
        print("0timeCount\(timeCount)")
        if timeCount > 0 {
            timerBtn.isEnabled = false
            timerBtn.setTitleAndColor(title: "重新发送(\(String(describing: timeCount)))", color: .x999999)
            timeCount-=1
        }
        else {
            //消除计时器（页面释放是必须调用这个方法，不让会让页面和定时器不会释放）
            timerBtn.isEnabled = true
            timerBtn.setTitleAndColor(title: "重新发送", color: .x999999)
            timerinvalidate()
        }
    }
}
